package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.MenuDao;
import com.itheima.dao.PermissionDao;
import com.itheima.dao.RoleDao;
import com.itheima.dao.UserDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Menu;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.MenuService;
import com.itheima.service.UserService;
import com.itheima.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Set;

@Service(interfaceClass = MenuService.class)
@Transactional
public class MenuServiceImpl implements MenuService {
    @Autowired
    private MenuDao menuDao;

    @Autowired
    private RoleDao roleDao;
    @Autowired
    private PermissionDao permissionDao;



    @Override
    public PageResult findMenuPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        // 执行分页查询获取到菜单项
        PageHelper.startPage(currentPage,pageSize);
        Page<Menu> page = menuDao.findMenuPage(queryString);
//         //获取用户对应的角色
//        for (User user : page) {
//            user.setPassword("想看吗?");
//            Set<Role> byUserId = roleDao.findByUserId(user.getId());
//            user.setRoles(byUserId);
//        }
        return new PageResult(page.getTotal(),page.getResult());

    }

    @Override
    public List<Menu> findMenuList2Show(String userName) {
        List<Menu> list = menuDao.findMenuList2Show(userName);

        return list;
    }

    @Override
    public List<Menu> childMenuById(Integer parentId) {
        return menuDao.childMenuById(parentId);
    }

    @Override
    public void add(Menu menu) {
        menuDao.add(menu);
    }
    @Override
    public void edit(Menu menu) {
//        // 关联是id字段,不需要改
//        if (menu.getLevel()==1){
//            // 一级菜单修改需要先改动关联表中的数据和子菜单的数据
//
//        }
        // 先保存主体
        menuDao.edit(menu);
    }
    @Override
    public void delete(Integer id) {
        int a = menuDao.fingReferByParentMenuId(id);
        int b = roleDao.fingReferByParentMenuId(id);
        if (a==0&&a==b){
            //两张关联表中都没有被引用
            menuDao.delete(id);
        }else {
            throw new RuntimeException("当前菜单被使用!");
        }




    }


}
